<template>
  <div>
    <el-dialog
      v-model="props.isShow"
      :title="props.isAdd ? '添加' : '编辑'"
      center
      :before-close="cancel"
    >
      <el-form ref="userRef" :model="cateForm" :rules="rules">
        <el-form-item label="上级分类" :label-width="formLabelWidth" prop="pid">
          <el-select placeholder="请选择上级分类" v-model="cateForm.pid">
            <el-option label="顶级分类" :value="0" />
            <el-option
              v-for="item in store.getters['cate/getCate']"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" :label-width="formLabelWidth" prop="catename">
          <el-input autocomplete="off" v-model="cateForm.catename" />
        </el-form-item>
        <!-- <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="onPreview"
            :on-change="changeInfo"
            :file-list="fileList"
            :limit="1"
            :auto-upload="false"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item> -->
        <el-form-item label="图片" :label-width="formLabelWidth">
          <!--  -->
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="onPreview"
            :on-change="onChange"
            :on-remove="onRemove"
            :on-exceed="onExceed"
            :auto-upload="false"
            :file-list="fileList"
            :limit="1"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="预览图片" />
          </el-dialog>
          <!--  -->
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-tooltip :content="'Switch value: ' + value" placement="top">
            <el-switch
              v-model="cateForm.status"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"
              :active-value="1"
              :inactive-value="2"
            />
          </el-tooltip>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(userRef)">取消</el-button>
          <el-button type="primary" @click="confirm(userRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { defineProps, defineEmits } from "vue";
import type { FormInstance, FormRules, UploadFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { cateadd, catelist, cateinfo, cateedit } from "../../request/api";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";

const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const value = ref("1");
const store = useStore();

// 调用仓库
const getCate = () => {
  store.dispatch("cate/getCateActions");
};
getCate();

const props = defineProps({
  isShow: Boolean,
  isAdd: Boolean,
});

let emit = defineEmits(["cancel"]);
let userRef = ref<FormInstance>();

// 双向数据绑定的数据
const cateForm = ref({
  pid: "", //       上级分类编号
  catename: "", //  商品分类名称
  img: "", //       图片(文件，一般用于二级分类)
  status: 1, //    状态            1正常2禁用
});

let rules = reactive<FormRules>({
  catename: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 6, message: "Length should be 2 to 6", trigger: "blur" },
  ],
  pid: [
    {
      required: true,
      message: "请选择上级菜单",
      trigger: "change",
    },
  ],
});

// 取消
const cancel = (formEl?: FormInstance | undefined) => {
  emit("cancel");

  cateForm.value = {
    pid: "", //       上级分类编号
    catename: "", //  商品分类名称
    img: "", //       图片(文件，一般用于二级分类)
    status: 1, //    状态            1正常2禁用
  };

  if (!formEl) return;

  // 清空表单验证
  userRef.value.resetFields();
};

// 数据回显
const lookup = async (id: number) => {
  let result: any = await cateinfo({ id });
  console.log(result);
  if (result.code == 200) {
    cateForm.value = result.list;
    // 修改的时候 需要id
    cateForm.value.id = id;
    // 图片回显
    cateForm.value.img ? (fileList.value = [{ url: cateForm.value.img }]) : "";
  }
};

// 添加和编辑事件
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((val) => {
    if (val) {
      if (props.isAdd) {
        console.log(cateForm.value);
        // return
        cateadd(cateForm.value).then((res) => {
          // console.log(res);
          if (res.code == 200) {
            // 成功 提示
            ElMessage.success(res.msg);
            cancel();
            getCate();
          } else {
          }
        });
      } else {
        cateedit(cateForm.value).then((res) => {
          // console.log(res);
          if (res.code == 200) {
            // 成功 提示
            ElMessage.success(res.msg);
            cancel();
            getCate();
          } else {
          }
        });
      }
    }
  });
};

// 可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性
defineExpose({
  lookup,
});

// 图片上传
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
// 用于清空图片
// const fileList: any = ref([]);
let fileList = ref();
// 上传图片成功时 将图片地址给img
// const changeInfo = (file: any) => {
//   console.log(file, "图片上传成功时返回的路径");
//   cateForm.value.img = file.raw;
// };

// // upload组件
// const onPreview = (file: any) => {
//   console.log(file, "文件的内容");
//   // // 打开预览弹窗
//   // dialogVisible = true;
//   // // 给弹窗赋值图片地址
//   // dialogImageUrl = file.url;
// };

// // 点击文件列表中已上传的文件时的钩子
// const uploadFile = (file: UploadFile) => {
//   console.log(file, "点击文件列表中已上传的钩子");
// };

// 上传图片相关的
// 预览
const onPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const onChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  cateForm.value.img = uploadFile.raw;
};

const onRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  cateForm.value.img = "";
};

const onExceed: UploadProps["onExceed"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  ElMessage({
    message: "只能上传一张图片",
    type: "error",
  });
};
</script>

<style lang="less" scoped></style>
